<template>
  <el-drawer v-model="drawer" title="Word Definition" :with-header="true" size="20%" class="custom-drawer" style=" color: var(--btn-text);background: var(--bg-color);
">

    <div v-if="loading">🔄 正在加载...</div>
    <div v-else-if="errorMessage" class="error-message">{{ errorMessage }}</div>
    <div v-else-if="result">
      <h2>{{ result.word }}</h2>
      <p v-if="phonetic">🔊 音标: {{ phonetic }}</p>

      <div v-for="(meaning, index) in result.meanings" :key="index">
        <h3>{{ meaning.partOfSpeech }}</h3>
        <ul>
          <li v-for="(definition, idx) in meaning.definitions" :key="idx">
            <p>📖 {{ definition.definition }}</p>
            <p v-if="definition.example">💡 示例: "{{ definition.example }}"</p>
          </li>
        </ul>
        <p v-if="meaning.synonyms.length">🔹 同义词: {{ meaning.synonyms.join(", ") }}</p>
        <p v-if="meaning.antonyms.length">🔸 反义词: {{ meaning.antonyms.join(", ") }}</p>
      </div>

      <audio v-if="audio" :src="audio" controls></audio>

      <div class="source-links">
        <h4>🔗 参考资料:</h4>
        <ul>
          <li v-for="(link, i) in result.sourceUrls" :key="i">
            <a :href="link" target="_blank">{{ link }}</a>
          </li>
        </ul>
      </div>
    </div>
  </el-drawer>
</template>

<script setup>
import { ref, defineProps, watch } from "vue";
import axios from "axios";
import { getWordDefine } from '../api/getAi.js'

// 接收父组件传递的 `word`
const props = defineProps({
  word: String,
  show: Boolean
});

const drawer = ref(props.show);
const result = ref(null);
const errorMessage = ref("");
const audio = ref(null);
const phonetic = ref("");
const loading = ref(false);

// 监听 `show` 变化，控制 `drawer` 显示
watch(() => props.show, (newValue) => {
  drawer.value = newValue;
  if (newValue && props.word) {
    fetchWordDefinition(props.word);
  }
});

// 获取单词定义
const fetchWordDefinition = async (word) => {
  errorMessage.value = "";
  result.value = null;
  audio.value = null;
  phonetic.value = "";
  loading.value = true;

  try {
    const response = await getWordDefine(word);
    const data = response;
    result.value = data;
    phonetic.value = data.phonetic || (data.phonetics[0]?.text ?? "");

    const sound = data.phonetics.find((p) => p.audio);
    if (sound) {
      audio.value = sound.audio;
    }
  } catch (error) {
    errorMessage.value = `❌ 未找到 ${word}，请检查拼写！`;
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
.custom-drawer h2 {
  margin: 12px 0;
}

.custom-drawer h3 {
  margin: 10px 0;
}

.custom-drawer p {
  margin: 8px 0;
}

.custom-drawer ul {
  padding-left: 20px;
}

.custom-drawer .source-links {
  margin-top: 16px;
}
</style>
